﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Product;
using Provenance.Read.Api.Application.Command.Product;
using Provenance.Read.Api.Application.CommandHandler.Provenance;
using Provenance.Read.Api.Dto.Product;

namespace Provenance.Read.Api.Application.CommandHandler.Product
{
    public class BackProductInfoCommandHandler : IRequestHandler<BackProductInfoCommand, ApiResult<BackProductInfoResponseDTO>>
    {
        private readonly IProductInfoRepository _productInfoRepository;
        private readonly ILogger<BackProductInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackProductInfoCommandHandler(IProductInfoRepository productInfoRepository, ILogger<BackProductInfoCommandHandler> logger, IMapper mapper)
        {
            _productInfoRepository = productInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<BackProductInfoResponseDTO>> Handle(BackProductInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _productInfoRepository.GetAsync(x => x.ProductInfoId == request.ProductInfoId);
                if(obj == null)
                {
                    return ApiResult<BackProductInfoResponseDTO>.Failure("Product not found");
                }
                var result= _mapper.Map<BackProductInfoResponseDTO>(obj);
                return ApiResult<BackProductInfoResponseDTO>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error in BackProductInfoCommandHandler:" + ex.Message);
                return ApiResult<BackProductInfoResponseDTO>.Failure("Error in BackProductInfoCommandHandler:" + ex.Message);
            }
        }
    }
}
